var localServer;

// Called onload to initialize local server and store variables
function init() {
  if (!window.google || !google.gears) {
    location.href="http://gears.google.com/?action=install&message=Offline%20Calendar%20Events" +
                  "&redirect=http://192.168.0.199/~jrp/gears/codelab/3/calendarout_wogears.html"
  } else {
    localServer = google.gears.factory.create("beta.localserver");
    textOut("Yeay, Google Gears is already installed.");
  }
}

// Utility function to output some status text.
function textOut(s) {
  var elm = document.getElementById("textOut");
  para = elm.appendChild(document.createElement("p"));
  para.appendChild(document.createTextNode(s));
}

var STORE_NAME = "calquery";
var MANIFEST_FILE = "manifest.json";

// Create the managed resource store
function createStore() {
  store = localServer.createManagedStore(STORE_NAME);
  store.manifestUrl = MANIFEST_FILE;
  store.checkForUpdate();

  var timerId = window.setInterval(function() {
    if (store.currentVersion) {
      window.clearInterval(timerId);
      textOut("The documents are now available offline. The version stored is: " + 
              store.currentVersion);
    } else if (store.updateStatus == 3) {
      textOut("Error: " + store.lastErrorMessage);
    }
  }, 500);  
}

var localDatabase;

function setupDatabase() {
  try {
    localDatabase = google.gears.factory.create("beta.database");
    if (localDatabase) {
      localDatabase.open('calgears');
      localDatabase.execute('create table if not exists Events ' +
                            '(title varchar(255), date varchar(24))');
    }
      
  } catch (e) {
    textOut('Failed to setup the database: ' + e.message);
  }
}
